<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI 聊天</title>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
            max-width: 800px;
            margin: 0 auto;
        }
        h1 {
            text-align: center;
            color: #333;
        }
        textarea {
            width: 100%;
            padding: 10px;
            font-size: 16px;
            border: 1px solid #ccc;
            border-radius: 4px;
            margin-bottom: 10px;
            box-sizing: border-box;
        }
        button {
            width: 100%;
            padding: 10px;
            font-size: 16px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #0056b3;
        }
        #response {
            margin-top: 20px;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            background-color: #f9f9f9;
        }
        /* Loading Spinner */
        #loading {
            display: none;
            margin: 20px auto;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #3498db;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 2s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
<h1>与 AI 聊天</h1>
<textarea id="userMessage" rows="4" placeholder="请输入您的问题..."></textarea><br><br>
<button onclick="sendMessage()">发送</button>

<div id="loading"></div>
<div id="response"></div>

<script>
    function sendMessage() {
        const message = document.getElementById('userMessage').value;
        if (!message) {
            alert('请输入消息');
            return;
        }

        // 显示加载动画
        document.getElementById('loading').style.display = 'block';

        fetch(`/ai/generate?message=${encodeURIComponent(message)}`)
            .then(response => response.text())
            .then(data => {
                // 隐藏加载动画
                document.getElementById('loading').style.display = 'none';
                document.getElementById('response').innerHTML = marked.parse(data);
            })
            .catch(error => {
                console.error('请求失败:', error);
                alert('请求失败，请稍后再试');
                // 隐藏加载动画
                document.getElementById('loading').style.display = 'none';
            });
    }
</script>
</body>
</html>